﻿using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Jinndev.UI;

namespace Jinndev {

    public class TileIdUI : BaseUIBehaviour {

        #region static
        public static readonly string PATH = "Prefab/UI/MapEditor/Tile/TileIdUI";

        /// <summary>
        /// 编辑、或者创建ID
        /// </summary>
        /// <param name="curId">传递-1表示创建，否则表示编辑</param>
        /// <param name="onConfirm">确定回调</param>
        public static TileIdUI Create(string curId, System.Action<string> onConfirm) {
            var com = UIManager.Instance.Add<TileIdUI>(PATH, UIParam.ModalPanel);
            com.Init(curId, onConfirm);
            return com;
        }
        #endregion


        public InputField inputID;
        public Text textError;

        private string curId;
        private System.Action<string> onConfirm;

        private void Awake() {
            textError.text = string.Empty;
            inputID.onValueChanged.AddListener(text => textError.text = string.Empty);
        }

        private void Start() {
            inputID.Select();
        }

        private void Update() {
            if (Input.GetKeyDown(KeyCode.KeypadEnter)) {
                OnClickConfirm();
            }
        }

        private void Init(string curId, System.Action<string> onConfirm) {
            this.curId = curId;
            this.onConfirm = onConfirm;

            if (curId == null) {
                inputID.text = MapUtil.NewTileID().ToString();
            }
            else {
                inputID.text = curId.ToString();
            }
        }

        public void OnClickConfirm() {
            string text = Validate(inputID.text);
            if (text != null) {
                Destroy(gameObject);
                onConfirm?.Invoke(text);
            }
        }

        private string Validate(string text) {
            //if (!int.TryParse(text, out int id) || id <= 0) {
            //    textError.text = "格式错误，需要为正整数";
            //    return -1;
            //}
            if (string.IsNullOrWhiteSpace(text)) {
                return null;
            }
            if (text == curId) {
                textError.text = "与原id相同";
                return null;
            }
            if (MapUtil.tileConfigs.ContainsKey(text)) {
                textError.text = "id已存在";
                return null;
            }
            return text;
        }
    }

}
